package cn.dlc.com.test;

import java.io.IOException;
import java.util.List;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;

public class ZookeeperDemo {

	private static final String connectString = "192.168.182.88:2181,192.168.182.89:2181,192.168.182.90:2181";
	private static final int sessionTimeout = 2000;
	
	private ZooKeeper zkClient = null;
	
	/**
	 * 初始化连接
	 * @throws IOException
	 */
	@Before
	public void init() throws IOException {
		zkClient = new ZooKeeper(connectString, sessionTimeout,new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				// 这个地方是收到事件通知后的回调函数，（自己的事件处理逻辑）
				// 事件的类型和发生事件的节点
				System.out.println(event.getType() + ": " + event.getPath());
				
				// 实现一直监听
				try {
					zkClient.getChildren("/", true);
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	/**
	 * 创建节点
	 * @throws Exception
	 */
	@Test
	public void testCreate() throws Exception {
		String data = "this is my first node from code";
		// 参数1：节点名称，参数2：数据，参数3：用这个就好了，参数4：节点类型，
		zkClient.create("/eclipse", data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		System.out.println("create node success!!");
	}
	
	/**
	 * 修改数据，修改节点存方的数据
	 * @throws Exception
	 */
	@Test
	public void testSetNode() throws Exception{
		zkClient.setData("/eclipse", "i".getBytes(),-1);
	}
	
	/**
	 * 查看节点数据
	 * @throws Exception
	 */
	@Test
	public void getChildrenNode() throws Exception {
		List<String> childNodes = zkClient.getChildren("/", true);
		for (String node : childNodes) {
			System.out.println(new String(node.getBytes()));
		}
		Thread.sleep(Long.MAX_VALUE);
	}
	
}
